<template>
  <el-dialog
    v-model="dialogVisible"
    title="系统设置"
    width="800px"
    :before-close="handleClose"
  >
    <el-tabs v-model="activeTab" tab-position="left">
      <!-- 常规设置 -->
      <el-tab-pane label="常规设置" name="general">
        <h3>壁纸设置</h3>
        <WallpaperSelector @select="handleWallpaperSelect" />
        
        <h3 class="mt-5">主题设置</h3>
        <el-form>
          <el-form-item label="主题颜色">
            <el-color-picker v-model="themeColor" />
          </el-form-item>
          <el-form-item label="深色模式">
            <el-switch v-model="darkMode" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <!-- 用户设置 -->
      <el-tab-pane label="用户设置" name="user">
        <h3>个人资料</h3>
        <el-form>
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="#"
              :http-request="uploadAvatar"
              :show-file-list="false"
            >
              <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="userInfo.nickname" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userInfo.email" disabled />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveUserProfile">保存资料</el-button>
          </el-form-item>
        </el-form>
        
        <h3 class="mt-5">账号安全</h3>
        <el-button @click="changePassword">修改密码</el-button>
        <el-button type="danger" @click="logout">退出登录</el-button>
      </el-tab-pane>
      
      <!-- 应用设置 -->
      <el-tab-pane label="应用设置" name="apps">
        <h3>应用设置</h3>
        <el-form>
          <el-form-item label="应用默认窗口大小">
            <el-radio-group v-model="defaultAppSize">
              <el-radio-button label="small">小</el-radio-button>
              <el-radio-button label="medium">中</el-radio-button>
              <el-radio-button label="large">大</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="默认打开方式">
            <el-select v-model="defaultOpenMode">
              <el-option label="窗口化" value="window" />
              <el-option label="全屏" value="fullscreen" />
            </el-select>
          </el-form-item>
        </el-form>
        
        <h3 class="mt-5">管理应用</h3>
        <el-table :data="installedApps" style="width: 100%">
          <el-table-column prop="name" label="应用名称" />
          <el-table-column prop="version" label="版本" width="120" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button @click="uninstallApp(scope.row.id)" type="danger" size="small">
                卸载
              </el-button>
              <el-button @click="handleAddToDesktop(scope.row)" size="small" :disabled="isAppOnDesktop(scope.row.id)">
                添加到桌面
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <!-- 关于 -->
      <el-tab-pane label="关于" name="about">
        <h2>Simple Tools Pro</h2>
        <p>版本: 1.0.0</p>
        <p>一个简洁高效的工具集成平台，帮助您提高工作效率。</p>
        <p>© 2023 SimpleTools团队</p>
        <p>
          <a href="#" @click="openGithub">GitHub</a> |
          <a href="#" @click="openDocumentation">文档</a>
        </p>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
      append-to-body
    >
      <el-form>
        <el-form-item label="当前密码">
          <el-input v-model="passwordForm.oldPassword" type="password" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" />
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, defineEmits } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import WallpaperSelector from './WallpaperSelector.vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { useWallpaperStore } from '@/stores/wallpaper'

const props = defineProps<{
  visible: boolean,
  initialTab?: string
}>()

const emit = defineEmits(['update:visible', 'close'])

const userStore = useUserStore()
const appStore = useAppStore()
const wallpaperStore = useWallpaperStore()

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 活动标签
const activeTab = ref(props.initialTab || 'general')

// 用户信息
const userInfo = ref({
  ...userStore.userInfo
})

// 修改密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 主题设置
const themeColor = ref('#409EFF')
const darkMode = ref(false)

// 应用设置
const defaultAppSize = ref('medium')
const defaultOpenMode = ref('window')

// 已安装应用
const installedApps = computed(() => appStore.installedApps)

// 判断应用是否在桌面上
const isAppOnDesktop = (appId: number) => {
  return appStore.isAppOnDesktop(appId)
}

// 修改密码弹窗
const passwordDialogVisible = ref(false)

// 关闭对话框
const handleClose = () => {
  emit('close')
}

// 壁纸选择
const handleWallpaperSelect = (wallpaper: string) => {
  wallpaperStore.setWallpaper(wallpaper)
  ElMessage.success('壁纸设置成功')
}

// 上传头像
const uploadAvatar = async (options: any) => {
  // 模拟上传成功
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    if (e.target) {
      userInfo.value.avatar = e.target.result as string
    }
  }
  reader.readAsDataURL(file)
}

// 保存用户资料
const saveUserProfile = async () => {
  try {
    await userStore.updateProfile(userInfo.value)
    ElMessage.success('资料保存成功')
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

// 修改密码
const changePassword = () => {
  passwordDialogVisible.value = true
}

// 更新密码
const updatePassword = async () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  try {
    await userStore.updatePassword(
      passwordForm.value.oldPassword,
      passwordForm.value.newPassword
    )
    
    passwordDialogVisible.value = false
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
    
    ElMessage.success('密码修改成功')
  } catch (error) {
    ElMessage.error('密码修改失败，请检查当前密码是否正确')
  }
}

// 退出登录
const logout = () => {
  userStore.logout()
  dialogVisible.value = false
}

// 卸载应用
const uninstallApp = async (appId: number) => {
  try {
    await appStore.uninstallApp(appId)
    ElMessage.success('应用卸载成功')
  } catch (error) {
    ElMessage.error('卸载失败，请重试')
  }
}

// 添加到桌面
const handleAddToDesktop = (app: any) => {
  appStore.addToDesktop(app)
  ElMessage.success('已添加到桌面')
}

// 打开GitHub
const openGithub = () => {
  window.open('https://github.com/simple-tools/simple-tools-pro', '_blank')
}

// 打开文档
const openDocumentation = () => {
  window.open('/docs', '_blank')
}
</script>

<style scoped>
.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.mt-5 {
  margin-top: 20px;
}
</style> 